import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { deletePermissionAPI, fetchPermissionListAPI } from '@/api/permissionAPI';
import type { Permission } from '@/type/permissionType';
import { transitionToTreeData } from '@/utils';
import { assignRoleAPI } from '@/api/roleAPI';
import { deleteEmployeeAPI } from '@/api/employeeAPI';
import { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';

type InitialState = {
  permissionTree: Permission[]
}

const initialState: InitialState = {
  permissionTree: [],
};

/**
 * @description 获取-权限点列表的异步函数
 * */
export const fetchPermissionList: any = createAsyncThunk('fetchPermissionList', async (_, { rejectWithValue }) => {
  try {
    const { data } = await fetchPermissionListAPI();
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 * @description 分配权限-角色的接口
 * */
export const assignRole: any = createAsyncThunk('assignRole', async ({ id, permIds }: { id: number, permIds: number[] }, { rejectWithValue }) => {
  try {
    const { message } = await assignRoleAPI(id, permIds);
    return message;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});


export const deletePermission: AsyncThunk<string, number, AsyncThunkConfig> = createAsyncThunk('deletePermission', async (id: number, { rejectWithValue }) => {
  try {
    const { message } = await deletePermissionAPI(id);
    return message;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const permissionStore = createSlice({
  name: 'permissionStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchPermissionList.fulfilled, (state: InitialState, action: PayloadAction<Permission[]>) => {
      const { payload } = action;
      state.permissionTree = transitionToTreeData(payload, 0);
    });
  },
});


export default permissionStore.reducer;
